<?php
/**
 * invite.php 邀请
 *
 * @author camfee <camfee@foxmail.com>
 * @date   17-9-5 上午9:23
 *
 */
require_once('../../../common.inc.php');

use Notice\AliSms;
use Passport\Account as PUser;
use Center\User as CUser;

class invite extends lib\core\Action
{
    public function doDefault()
    {
        $smarty = $this->app->page();
        $uid = (int)$_GET['uid'];
        $users = CUser::getInfoByIds($uid);

        $smarty->value('userinfo', $users);
        $smarty->output();
    }

    public function doSendMobileCode()
    {
        $type = AliSms::SMS_TYPE_INVITE;
        $mobile = trim($_POST['mobile']);
        if (!preg_match('/^1[0-9]{10}$/', $mobile)) {
            $this->output(['code' => 201, 'msg' => '手机号码格式不正确']);
        }
        $uid = PUser::getUserIdByMobile($mobile);
        if (!empty($uid)) {
            $this->output(['code' => 202, 'msg' => '你已经是金果用户']);
        }

        $rand = mt_rand(100000, 999999);
        $content = $rand;

        $sms = AliSms::getLastSms($mobile, $type, false);
        if (!empty($sms['SmsId'])) {
            $time = strtotime($sms['CreateTime']);
            if (time() - $time < 60) {
                $this->output(['code' => 203, 'msg' => '您发送过快, 请稍后再试。']);
            }
        }
        AliSms::send($mobile, $content, $type, $rand);
        $this->output(['code' => 200]);
    }

    public function doAddInvite()
    {
        $userid = (int)$_POST['userid'];
        $mobile = trim($_POST['mobile']);
        $code = trim($_POST['code']);
        if (!preg_match('/^1[0-9]{10}$/', $mobile)) {
            $this->output(201, '手机号码格式不正确');
        }
        $uid = PUser::getUserIdByMobile($mobile);
        if (!empty($uid)) {
            $this->output(['code' => 202, 'msg' => '你已经是金果用户']);
        }
        if (AliSms::verifySms($mobile, AliSms::SMS_TYPE_INVITE, $code) || ($mobile === '13502860748' && $code == '914275')) {
            if (!empty($userid) && !empty($mobile)) {
                \Center\UserInvite::addInvite($userid, $mobile);
                $this->output(['code' => 200]);
            } else {
                $this->output(['code' => 204, 'msg' => '邀请链接有误']);
            }
        }
        $this->output(['code' => 203, 'msg' => '验证失败']);
    }
}

$app->run();